package com.sikaryofficial.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.sikaryofficial.common.core.constant.GatewayFilterOrdered;
import com.sikaryofficial.common.core.constant.SecurityConstants;
import com.sikaryofficial.common.core.secure.SecureComponent;
import com.sikaryofficial.common.core.secure.SecureComponentFactory;
import com.sikaryofficial.gateway.config.properties.SecureProperties;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPatternParser;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 定制密码过滤器
 * <p>
 * 1、请求解密
 * 2、响应加密
 * <p>
 * 目前优先做 2
 *
 * @author qinjinyuan
 */
@Component
@ConditionalOnProperty(value = SecureProperties.RESPONSE_ENABLE, havingValue = "true")
@Slf4j
public class ResponseEncryptFilter implements GlobalFilter, Ordered {

    private SecureComponent secureComponent;

    @Resource
    private SecureProperties secureProperties;

    public SecureComponent getSecureComponent() {
        if (Objects.isNull(secureComponent)) {
            secureComponent = SecureComponentFactory.get(secureProperties.getAlgorithm());
        }
        return secureComponent;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求体
        ServerHttpRequest request = exchange.getRequest();
        MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
        if (!secureProperties.enableEncryptResponseParam() || isNotNeedEncrypt(request.getURI())) {
            return chain.filter(exchange);
        }
        // 判定是否为json请求
        if ((mediaType != null
                && mediaType.includes(MediaType.APPLICATION_JSON) ||
                request.getMethod() == HttpMethod.GET
        )
                && isNeedEncrypt(request.getURI())) {
            // 根据具体业务内容，修改响应体
            return modifyResponseBody(exchange, chain);
        }
        return chain.filter(exchange);
    }

    /**
     * 是否需要加密
     *
     * @param uri
     * @return
     */
    private boolean isNeedEncrypt(URI uri) {
        // 空指针检查
        if (uri == null || secureProperties == null) {
            return false;
        }
        // 缓存并转换为不可变集合
        List<String> encryptUriList = Collections.unmodifiableList(secureProperties.getEncryptUriList());
        if (CollUtil.isEmpty(encryptUriList)) {
            return false;
        }
        // 获取路径
        String path = uri.getPath();
        if (path == null) {
            return false;
        }
        for (String pathPattern : encryptUriList) {
            if (isMatch(path, pathPattern)) {
                return true;
            }
        }
        return false;
    }

    private boolean isNotNeedEncrypt(URI uri) {
        List<String> encryptUriList = secureProperties.getNoEncryptUriList();
        if (CollUtil.isEmpty(encryptUriList)) {
            return false;
        }
        String path = uri.getPath();
        for (String pathPattern : encryptUriList) {
            if (isMatch(path, pathPattern)) {
                return true;
            }
        }
        return false;
    }

    private boolean isMatch(String path, String pathPattern) {
        // 这里需要根据whiteListed的格式来判断和匹配
        // 对于简单IP可以直接比较，对于范围和CIDR需要额外逻辑
        // ...
        return PathPatternParser.defaultInstance.parse(pathPattern).matches(PathContainer.parsePath(path));
    }

    @Override
    public int getOrder() {
        return GatewayFilterOrdered.RESPONSE_ENCRYPT;
    }

    /**
     * 修改响应体
     *
     * @param exchange
     * @param chain
     * @return
     */
    private Mono<Void> modifyResponseBody(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        originalResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator response = buildResponse(originalResponse, bufferFactory);
        return chain.filter(exchange.mutate().response(response).build());
    }

    private ServerHttpResponseDecorator buildResponse(ServerHttpResponse originalResponse, DataBufferFactory bufferFactory) {
        return new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (Objects.equals(getStatusCode(), HttpStatus.OK) && body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        DataBufferUtils.release(join);
                        // 流转为字符串
                        String responseData = new String(content, StandardCharsets.UTF_8);
                        //加密数据
                        responseData = encryptResponse(responseData);
                        byte[] uppedContent = responseData.getBytes(StandardCharsets.UTF_8);
                        originalResponse.getHeaders().setContentLength(uppedContent.length);
                        // 设置响应头表示已加密
                        originalResponse.getHeaders().add(SecurityConstants.RESPONSE_HEADER_ENCRYPTED, "true");
                        originalResponse.getHeaders().add(SecurityConstants.RESPONSE_HEADER_ALGORITHM, secureProperties.getAlgorithm().toString());
                        return bufferFactory.wrap(uppedContent);
                    }));
                } else {
                    log.error("获取响应体数据 ：" + getStatusCode());
                }
                return super.writeWith(body);
            }

            @Override
            public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
                return writeWith(Flux.from(body).flatMapSequential(p -> p));
            }
        };
    }

    /**
     * 响应加密
     * @param originalResponseBody
     * @return
     */
    private String encryptResponse(String originalResponseBody) {
        return getSecureComponent().encrypt(originalResponseBody);
    }

    private void dealData(String originalResponseBody) {
        Map map = JSON.parseObject(originalResponseBody);
        //处理返回的数据
        Object data = map.get("data");
        if (data != null) {
            map.put("data", getSecureComponent().encrypt(data.toString()));
        }
        //处理返回的数据
        Object rows = map.get("rows");
        if (rows != null) {
            map.put("rows", getSecureComponent().encrypt(rows.toString()));
        }
    }
}
